﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Transactions;
using Petshop.Backend.Data;


namespace Petshop.Backend.Logic
{
    public class OrderService
    {

        private readonly IDatabaseSession _databaseSession;

        public OrderService():this(new DatabaseSession())
        {
           
        }
        public OrderService(IDatabaseSession databaseSession)
        {
            _databaseSession = databaseSession;
        }
        public Order CreateOrder(Order order)
        {
            Order newOrder = null;
            using (var ts = new TransactionScope(TransactionScopeOption.Required))
            {
                using (var repOrder = new OrderRepository(_databaseSession))
                {
                    using (var repItem = new ItemRepository(_databaseSession))
                    {
                       repOrder.Insert(order);
                        foreach (var lineItem in order.LineItems)
                        {
                            repItem.DecreaseStockForItem(lineItem.ItemId, lineItem.Quantity);
                        }
                        _databaseSession.Context.SaveChanges();
                        newOrder=repOrder.RetrieveById(order.OrderId);
                        ts.Complete();
                        
                    }
                }
            }
            return newOrder;
        }

        public bool VerifyAvailability(string itemId, int cartItemQuantity)
        {
            using (var rep = new ItemRepository(_databaseSession))
            {
                return rep.VerifyAvailability(itemId,cartItemQuantity);
            }
        }
    }
}
